#include "maindialog.h"
#include "ui_maindialog.h"
#include <QDebug>
#include <QTcpSocket>

MainDialog::MainDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::MainDialog)
{
    ui->setupUi(this);

    //创建监听套接字
    m_sock = new QTcpServer(this);

    connect(m_sock,&QTcpServer::newConnection,this,&MainDialog::acceptConnect);

    //监听
    m_sock->listen(QHostAddress::Any,8888);

}

MainDialog::~MainDialog()
{
    delete ui;
}

void MainDialog::acceptConnect()
{
      qDebug() << "有一个新的客户端请求到来！";

       //创建连接套接字,进行收发数据
      QTcpSocket* sockConn =  m_sock->nextPendingConnection();

      connect(sockConn,&QTcpSocket::readyRead,this,&MainDialog::recvMsg);
      connect(sockConn,&QTcpSocket::disconnected,this,&MainDialog::connectClosed);

      //用容器收到所有客户端的套接字,利用尾插
      m_clients.push_back(sockConn);

      ui->labelClients->setText(QString("在线人数: %1").arg(m_clients.size()));

}


void MainDialog::on_btnSend_clicked()
{
    //将聊天消息发送给所有在线客户端
    QString msg = ui->edtMsg->toPlainText();

    for(QTcpSocket* sock: m_clients)
    {
        sock->write(msg.toUtf8());
    }
    ui->edtMsg->clear();

}

void MainDialog::recvMsg()
{
    //获取信号发射者的指针
    QTcpSocket* sock =  qobject_cast<QTcpSocket*>(sender()); //向下转型

    //接收当前所有新数据
    QByteArray data = sock->readAll();

    //在聊天记录框中显示
    ui->edtRecord->appendPlainText(QString::fromUtf8(data) + "\n\n");

    for(QTcpSocket* sock: m_clients)
    {
        sock->write(data);
    }
}

void MainDialog::connectClosed()
{
    //获取信号发射者的指针
    QTcpSocket* sock =  qobject_cast<QTcpSocket*>(sender()); //向下转型

    m_clients.removeOne(sock); //从客户端链表中删除当前下线的客户端

    ui->labelClients->setText(QString("在线人数:%1").arg(m_clients.size()));

    sock->deleteLater();
}
